

/**
 * 1. 提取css 和js
 * 2. 写入到一个新的文件中；
* @description
*/
const fs = require('fs')
class InjectHtml {
  constructor({ outpath, data, template }) {
    this.outpath = outpath;
    this.data = data;
    this.template = template;
  }
  // 封装一个读取文件的方法
  myReadfile(src) {
    return new Promise((resolve, reject) => {
      fs.readFile(src, (err, data) => {
        if (err) {
          reject(err)
          return
        }
        resolve(data.toString())
      })
    })
  }

  // 获取文件内容的方法
  async getInner(tag, path) {
    // 遍历读取内容，拼接标签  <style></style>
    let str = `<${tag}>`;
    for (let file of path) {
      str += await this.myReadfile(file)
    }
    str += `</${tag}>`
    return str;
  }

  // 写入文件的方法
  async myWritefile() {
    // 先获取到所有的内容
    let html = await this.myReadfile(this.template);
    // 通过遍历路径 一步一步替换内容
    for (let val of this.data) {
      let text = await this.getInner(val.type, val.file)
      html = html.replace(`<!-- ${val.type} -->`, text)
    }
    return html;
  }
}

const inject = new InjectHtml({
  template: './src/index.html',
  outpath: './result.html',
  data: [
    {
      type: 'style',
      file: ['./src/static/css/index.css']
    },
    {
      type: 'script',
      file: ['./src/static/js/index.js']
    }
  ]
})

inject.myWritefile().then(res => {
  console.log(res, 'res')
  fs.writeFileSync('./out.html', res)
})
